<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/5/25
 * Time: 23:36
 * Mail:87658989@qq.com
 */

namespace app\mobile\controller;
use think\Db;
use think\Request;
use think\Validate;
use EasyWeChat\Factory;

class Question extends Base
{
    public function index(){
        $action   = input('active_id',1);
        $fromWay  = input('fromway',0);
        $params   = 'active_id='.$action.'&fromway='.$fromWay;
        $url      = url('mobile/question/index',$params,'html',true);
        $this->assign('shareUrl',$url);
        $url2     = urlencode($url);
        $type     = input('action');
        $gallery  = Db::name('gallery_action')->find($action);
        $noticeUrl = 'https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=wxfebffdb82a23a32a&scene=1000&template_id=802xVIZzAnXhPqb25Dt8ppqYDpPvl6LxrIy8VP997gY&redirect_url='.$url2.'&reserved=test#wechat_redirect';
        $this->assign('url',$noticeUrl);
        if($type=='confirm' || $type=='notice'){
            if($type=='notice'){
                $noticeUrl = 'https://mp.weixin.qq.com/mp/subscribemsg?action=get_confirm&appid=wxfebffdb82a23a32a&scene=1000&template_id=802xVIZzAnXhPqb25Dt8ppqYDpPvl6LxrIy8VP997gY&redirect_url='.$url2.'&reserved=test#wechat_redirect';
                $this->redirect($noticeUrl);
            }
            $openId      = input('openid');
            $accessToken = $this->app->access_token;
            $token       = $accessToken->getToken();
            $url         = 'https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token=' . $token['access_token'];
            $backIid     = session('back_id');
            $data = [
                'touser'      => $openId,
                'template_id' => '802xVIZzAnXhPqb25Dt8ppqYDpPvl6LxrIy8VP997gY',
                'url' => 'http://www.aierfen.com/mobile/question/viewAnswer/active_id/'.$action.'/id/'.$backIid,
                'title'=>$gallery['gallery_name'],
                'scene' => 1000,
                'data' => [
                    'content' => [
                        "value" => '报名成功'
                    ]
                ],
            ];
            $data_string = json_encode($data);
            $this->vpost($url, $data_string);
        }
        $list     = Db::name('gallery')
            ->where('action_id',$action)
            ->whereNull('delete_time')->order('rank')
            ->select();
        $question = [];
        $validate = [];
        $filter   = [];
        $keyField = [];
        foreach ($list as $value){
            $typeArr = ['input','radio','checkbox','text','file','option'];
            if(in_array($value['type'],$typeArr)){
                $rule =!empty($value['tag']) ? $value['name'].'|'.$value['tag'] : $value['name'].'|必填项';
                $validate[$rule]      = $value['rule'];
                $filter[$value['name']]['type'] = $value['type'];
                $ruleId[$value['name']] = $value['id'];
                if($value['is_key']==1) $keyField[] = $value['name'];
            }
            $temp    = $value;
            if(!empty($value['paragraph'])){
                $temp['paragraph'] = explode('#',$value['paragraph']);
            }
            if(!empty($value['paragraph'])){
                $temp['paragraph'] = explode('#',$value['paragraph']);
            }
            if(!empty($value['option_text'])){
                $arr = explode('#',$value['option_text']);
                $drr = [];
                foreach ($arr as $vv){
                    $crr = [];
                    $brr = explode('-',$vv);
                    $crr['tag']   = $brr[0];
                    $crr['value'] = $brr[1];
                    $drr[] = $crr;
                }
                $temp['option_text'] = $drr;
            }
            $question[] = $temp;
        }
        if(Request::instance()->isPost()){
            $v = new \app\mobile\validate\Question();
            $t = Request::instance()->param();
            if(!$v->check($t,$validate)){
                $err = $v->getError();
                if(is_array($err)){
                    $errMsg = [];
                    foreach ($err as $a=>$b){
                        $errMsg[] = $b;
                    }
                    return $this->retErr(implode(',',$errMsg));
                }else{
                    return $this->retErr($err);
                }
            }
            $data = $v->getRuleDate($validate,$t);
            $rData= [];
            foreach ($ruleId as $k=>$v){
                $temp = [];
                $temp['gallery_id'] = $v;
                $temp['content']    = isset($data[$k]) ? $data[$k] : '';
                $rData[] = $temp;
            }
            $keyStr = [];
            foreach ($keyField as $v){
                $keyStr[] = $data[$v];
            }
            $json             = serialize($rData);
            $dd['action_id']  = $action;
            $dd['content']    = $json;
            $dd['key_str']    = implode(',',$keyStr);
            $whereHas['action_id'] = $action;
            $whereHas['key_str']   = $dd['key_str'];
            $hasInput = Db::name('gallery_answer')->where($whereHas)->find();
            if(!empty($hasInput)){
                return $this->retErr('你已提交过报名');
            }
            $dd['from_way']   = $fromWay;
            $id = Db::name('gallery_answer')->insertGetId($dd);
            session('back_id',$id);
            return $this->retSucc('ok',['back_id'=>$id]);
        }
        $realCount   = Db::name('gallery_answer')->where('action_id',$action)->count();
        $viewCounts  = floor((time() - 1528210484)/10);
        $atendCounts = 80 + $realCount;
        $this->assign('viewCounts',$viewCounts);
        $this->assign('atendCounts',$atendCounts);
        $this->assign('question',$question);
        $this->assign('gallery',$gallery);
        $this->assign('action',$action);
        $this->assign('fromway',$fromWay);
        return $this->fetch();
    }

    public function viewAnswer(){
        $action   = input('active_id');
        $gid      = input('id');
        $params   = 'active_id='.$action;
        $url      = url('mobile/question/index',$params,'html',true);
        $this->assign('shareUrl',$url);
        $gallery  = Db::name('gallery_action')->find($action);
        $list     = Db::name('gallery')
            ->where('action_id',$action)
            ->whereNull('delete_time')->order('rank')
            ->select();
        $where['id']        = $gid;
        $where['action_id'] = $action;
        $answer   = Db::name('gallery_answer')->where($where)->find();
        $an       = [];
        $answerArr= unserialize($answer['content']);
        foreach ($answerArr as $v1){
            $an[$v1['gallery_id']] = $v1['content'];
        }
        $question = [];
        $validate = [];
        $filter   = [];
        $keyField = [];
        foreach ($list as $value){
            $typeArr = ['input','radio','checkbox','text','file','option'];
            if(in_array($value['type'],$typeArr)){
                $rule =!empty($value['tag']) ? $value['name'].'|'.$value['tag'] : $value['name'].'|必填项';
                $validate[$rule]      = $value['rule'];
                $filter[$value['name']]['type'] = $value['type'];
                $ruleId[$value['name']] = $value['id'];
                if($value['is_key']==1) $keyField[] = $value['name'];
                isset($an[$value['id']]) && $value['input_value'] = $an[$value['id']];
            }
            $temp    = $value;
            if(!empty($value['paragraph'])){
                $temp['paragraph'] = explode('#',$value['paragraph']);
            }
            if(!empty($value['paragraph'])){
                $temp['paragraph'] = explode('#',$value['paragraph']);
            }
            if(!empty($value['option_text'])){
                $arr = explode('#',$value['option_text']);
                $drr = [];
                foreach ($arr as $vv){
                    $brr = explode('-',$vv);
                    $drr[$brr[1]] = $brr[0];
                }
                $temp['input_value'] = $drr[$value['input_value']];
            }
            $question[] = $temp;
        }
        $realCount   = Db::name('gallery_answer')->where('action_id',$action)->count();
        $viewCounts  = floor((time() - 1528210484)/10);
        $atendCounts = 80 + $realCount;
        $this->assign('viewCounts',$viewCounts);
        $this->assign('atendCounts',$atendCounts);
        $this->assign('question',$question);
        $this->assign('gallery',$gallery);
        $this->assign('action',$action);
        return $this->fetch();
    }
}
